<template>
  <div class="avatar">
    <!-- 用户信息 -->
    <el-dropdown placement="bottom-start" @command="handleCommand">
      <div class="info">
        <img v-if="!userInfo.avatar" class="img" :src="squareUrl" />
        <el-image v-else class="img"
          :src="`http://localhost:3000/image/getavatar/${encodeURIComponent(userInfo.avatar)}`" />
        <div class="msg">
          <span
            style="display:inline-block;width: 100px;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;margin-bottom: 4px;">
            {{ userInfo.user_name }}
          </span>
          <div style="font-size: 12px;">
            <span
              style="display:inline-block;width: 60px;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;margin-right: 4px;">{{
                userInfo.institute_name }}</span>
            <span v-if="userInfo.user_auth == 'student_per'"
              style="display:inline-block;width: 40px;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">
              {{ userInfo.student_name }}
            </span>
            <span v-if="userInfo.user_auth == 'teacher_per'"
              style="display:inline-block;width: 40px;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">
              {{ userInfo.teacher_name }}
            </span>
          </div>
        </div>
      </div>
      <el-dropdown-menu slot="dropdown" style="color: #cceabb;">
        <el-dropdown-item command="changeUserInfo">修改用户信息</el-dropdown-item>
        <el-dropdown-item command="changePassword">修改密码</el-dropdown-item>
        <el-dropdown-item command="logOut" divided>退出登录</el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>
    <!-- 修改密码弹框 -->
    <el-dialog title="修改密码" :visible.sync="dialogFormVisible" :show-close='false'>
      <el-form :model="form" status-icon :rules="rules" ref="form">
        <el-form-item prop="oldPassword">
          <el-input v-model="form.oldPassword" autocomplete="off" placeholder="旧密码" type="password"></el-input>
        </el-form-item>

        <el-form-item prop="newPassword">
          <el-input v-model="form.newPassword" autocomplete="off" placeholder="新密码" type="password"></el-input>
        </el-form-item>

        <el-form-item prop="confirmPassword">
          <el-input v-model="form.confirmPassword" autocomplete="off" placeholder="确认密码" type="password"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="changePwd('form')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改用户信息弹框 -->
    <el-dialog title="修改用户信息" :visible.sync="dialogUser" :show-close='false'>
      <el-form :model="userForm" status-icon :rules="rules" ref="userForm">
        <el-form-item class="upload" label="头像：">
          <div style="
                  display: flex;
                  justify-content: center;
                  align-items: center;
                ">
            <el-button @click="dialogCropper = true" id="btn" style="display: none;"></el-button>
            <label for="btn">
              <el-avatar :size="100" v-show="!fileContent"
                :src="userInfo.avatar ? 'http://localhost:3000/image/getavatar/' + encodeURIComponent(userInfo.avatar) : squareUrl"
                shape="square" :img="userInfo.avatar" style="margin-right: 40px;cursor: pointer;"></el-avatar>

              <el-avatar :size="100" v-show="fileContent" :src="fileContent" shape="square" :img="fileContent"
                style="margin-right: 40px;cursor: pointer;"></el-avatar>
            </label>

            <el-button type="success" plain @click="uploadImg">确认上传</el-button>
          </div>
        </el-form-item>

        <el-form-item prop="user_name" label="昵称">
          <el-input v-model="userForm.user_name" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item prop="signature" label="个性签名">
          <el-input v-model="userForm.signature" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogUser = false">取 消</el-button>
        <el-button type="primary" @click="changeInfo('userForm')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 图片裁剪弹框 -->
    <Cropper :dialogCropper="dialogCropper"
      :imgUrl="userInfo.avatar ? 'http://localhost:3000/image/getavatar/' + encodeURIComponent(userInfo.avatar) : squareUrl"
      :fixedNumber="[1, 1]" :loading="loading" @closeDialog="dialogCropper = false" @blobData="handleBlobData"
      v-if="userInfo.avatar">
    </Cropper>
    <!-- 通知 -->
    <div class="icon">
      <el-badge is-dot style="margin-top: 10px;margin-right: 40px;">
        <i class="el-icon-bell" @click="goMessage"></i>
      </el-badge>
    </div>

  </div>
</template>

<script>
import Cropper from "./Cropper.vue";

export default {
  name: 'UserAvatar',
  components: {
    Cropper
  },
  data() {
    return {
      userInfo: {},
      dialogFormVisible: false,
      form: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      dialogUser: false,
      userForm: {
        user_name: '',
        signature: ''
      },
      rules: {
        oldPassword: [
          { required: true, message: '旧密码不能为空', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '新密码不能为空', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '确认密码不能为空', trigger: 'blur' }
        ],
        user_name: [
          { required: true, message: '昵称不能为空', trigger: 'blur' }
        ],
        signature: [
          { required: true, message: '个性签名不能为空', trigger: 'blur' }
        ],
      },
      fileData: '',
      fileContent: '',

      // 裁剪组件的基础配置option
      dialogCropper: false,
      loading: false,
      squareUrl:
        "https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png",
    }
  },
  methods: {
    goMessage() {
      this.$router.push(
        {
          path: '/home/message',
          // query: { id: keyPath[0] }
        }
      )
      this.$emit("transfer", '/home/message');
    },
    //下拉菜单选择
    async handleCommand(command) {
      if (command == "changeUserInfo") {
        this.$message('click on item ' + command);
        this.userForm = {
          user_name: this.userInfo.user_name,
          signature: this.userInfo.signature
        }
        this.dialogUser = true;
      }
      if (command == 'changePassword') {
        this.dialogFormVisible = true;
      }
      if (command == 'logOut') {
        await this.logOut();
      }
    },
    //退出登录
    async logOut() {
      // 清空本地存储
      localStorage.removeItem("token");
      localStorage.removeItem("userInfo");
      localStorage.removeItem("refreshtoken");
      // 修改vuex为空对象
      this.$store.commit("setUser", {});
      // 页面跳转
      this.$router.push('/login')
      this.$message({
        showClose: true,
        message: '您已退出登录',
        type: 'success'
      });
    },
    //修改密码
    changePwd(form) {
      this.$refs[form].validate(async (valid) => {
        if (valid) {
          if (this.form.newPassword == this.form.confirmPassword) {
            let obj = {
              oldPassword: this.Rsa.noTokenRsa(this.form.oldPassword),
              newPassword: this.Rsa.noTokenRsa(this.form.newPassword),
              confirmPassword: this.Rsa.noTokenRsa(this.form.confirmPassword),
              user_id: this.userInfo.user_id
            }
            let res = await this.$axios.post('/mycourse/changepwd', obj)
            console.log(res);
            if (res.code == 200) {
              this.dialogFormVisible = false
              await this.logOut()
            } else {
              this.$message.error(res.msg)
            }
          } else {
            this.$message.error('两次密码输入不同')
          }
        } else {
          this.$message.error('存在未填项')
          return false;
        }
      });
    },
    //修改用户信息
    changeInfo(form) {
      this.$refs[form].validate(async (valid) => {
        if (valid) {
          if (this.userForm.user_name == this.userInfo.user_name && this.userForm.signature == this.userInfo.signature) {
            this.$emit("transfer", 'update');
          } else {
            let res = await this.$axios.post('/mycourse/changeinfo', { ...this.userForm, user_id: this.userInfo.user_id, user_auth: this.userInfo.user_auth })
            console.log(res);
            if (res.code == 200) {
              this.userInfo = { ...this.userInfo, user_name: res.data.user_name, signature: res.data.signature }
              let result = await this.$axios.post('/mycourse/submit', { user_id: this.userInfo.user_id, user_auth: this.userInfo.user_auth, user_name: this.userInfo.user_name })
              if (result.code == 200) {
                localStorage.setItem("token", result.token);
                localStorage.setItem("refreshtoken", result.refreshToken);
                localStorage.setItem("userInfo", result.user_info);
                let reslut = await this.$axios.post("/login/userInfo", { user_info: localStorage.getItem("userInfo") });
                this.$store.commit("setUser", reslut.user_info);
                this.userInfo = {
                  ...JSON.parse(JSON.stringify(this.$store.state.user_info))
                };
                this.$emit("transfer", 'update');
              }
            }
          }
        } else {
          this.$message.error('存在未填项')
          return false;
        }
      });
      this.dialogUser = false
    },
    // 裁剪图片后返回的blob
    async handleBlobData(blob) {
      // 处理 Blob 对象
      console.log(blob);
      const reader = new FileReader();
      reader.onload = () => {
        this.fileContent = reader.result;
      };
      reader.readAsDataURL(blob);
      let fd = new FormData()
      fd.append('avatar', blob)
      this.fileData = fd;
      console.log(this.fileData);
    },
    // 上传图片
    async uploadImg() {
      let res = await this.$axios.post(`/mycourse/uploadavatar/?user_id=${this.userInfo.user_id}&user_auth=${this.userInfo.user_auth}`, this.fileData)
      console.log(res);
      if (res.code == 200) {
        let result = await this.$axios.post('/mycourse/submit', { user_id: this.userInfo.user_id, user_auth: this.userInfo.user_auth, user_name: this.userInfo.user_name })
        if (result.code == 200) {
          localStorage.setItem("token", result.token);
          localStorage.setItem("refreshtoken", result.refreshToken);
          localStorage.setItem("userInfo", result.user_info);
          let reslut = await this.$axios.post("/login/userInfo", { user_info: localStorage.getItem("userInfo") });
          this.$store.commit("setUser", reslut.user_info);
          this.userInfo = {
            ...JSON.parse(JSON.stringify(this.$store.state.user_info))
          };
          this.$emit("transfer", 'update');
          this.loading = false
        }
        this.$message.success('上传成功!')
        console.log(this.userInfo);
      }
    },
  },
  async mounted() {
    if (Object.keys(JSON.parse(JSON.stringify(this.$store.state.user_info))).length == 0) {
      let res = await this.$axios.post("/login/userInfo", { user_info: localStorage.getItem("userInfo") })
      console.log(res);
      this.$store.commit("setUser", res.user_info);
    }
    // 如果想要使用那么就通过JSON进行深度遍历
    console.log(JSON.parse(JSON.stringify(this.$store.state.user_info)));
    this.userInfo = {
      ...JSON.parse(JSON.stringify(this.$store.state.user_info))
    };
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.img {
  width: 60px;
  height: 60px;
  border-radius: 50%;
}

.avatar {
  width: 260px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

.info {
  width: 165px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
}

.msg {
  color: rgba(63, 63, 68, 1);
  font-size: 14px;
  font-weight: 400;
}

.icon {
  font-size: 25px;
  cursor: pointer;
}

.upload {
  display: flex;
}
</style>